package com.niguang.work.labour.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.dayu.api.SmsTemplate;
import com.aliyun.dayu.mode.SendSmsResponse;
import com.niguang.work.labour.common.constant.ResultCode;
import com.niguang.work.labour.common.pojo.Result;
import com.niguang.work.labour.common.util.RegexUtils;
import com.niguang.work.labour.sms.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {


    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @Resource
    private SmsTemplate smsTemplate;

    @Override
    public Result sendSms(@NotNull @RequestParam String userPhone) {
        userPhone = RegexUtils.removeSpace(userPhone);
        if (!RegexUtils.checkPhone(userPhone)) {
            return Result.build(ResultCode.PARAM_ERROR, "手机格式不正确!");
        }
        if (StringUtils.isNotBlank(getSmsCode(userPhone))) {
            Long expire = redisTemplate.getExpire(userPhone, TimeUnit.SECONDS);
            return Result.build(ResultCode.PARAM_ERROR, "您已获取过验证码，请" + expire + "秒后再获取~");
        }
        try {
            String code = smsCode(userPhone);
            SendSmsResponse sendSmsResponse = smsTemplate.sendSmsCode(userPhone, code);
            log.info("短信发送返回结果：{}", JSON.toJSONString(sendSmsResponse));
            if (!StringUtils.equalsIgnoreCase(sendSmsResponse.getCode(), "OK")) {
                redisTemplate.delete(userPhone);
                return Result.build(ResultCode.PARAM_ERROR, "您手机号码[" + userPhone + "]短信验证码获取频率过多，请稍后重试~");
            }
            return Result.build(ResultCode.SUCCESS, "获取验证码成功！");
        } catch (Exception e) {
            log.error("短信验证码获取异常：{}", e);
        }
        return Result.failed("短信验证码获取失败，请稍后重试~");
    }


    /**
     * 生成6位数字验证码
     * 缓存验证码
     *
     * @param userPhone
     * @return
     */

    private String smsCode(String userPhone) {
        //生成验证码
        String code = String.format("%.0f", (Math.random() * 9000 + 100000));
        //将验证码以<key,value>形式缓存到redis
        redisTemplate.opsForValue().set(userPhone, code, 60, TimeUnit.SECONDS);
        return code;
    }

    @Override
    public String getSmsCode(String userPhone) {
        return redisTemplate.opsForValue().get(userPhone);
    }


}
